package com.zm.admin.zmeng.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zm.admin.annotation.SysLogTag;
import com.zm.admin.zmeng.domain.ZmRole;
import com.zm.admin.zmeng.domain.ZmRoleMenu;
import com.zm.admin.zmeng.dto.RoleDto;
import com.zm.admin.zmeng.dto.UserDto;
import com.zm.admin.zmeng.mapper.ZmRoleMapper;
import com.zm.admin.zmeng.mapper.ZmRoleMenuMapper;
import com.zm.admin.zmeng.service.ZmRoleService;
import com.zm.admin.utils.ResultBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

/***
 *
 * @Auther: MuYun
 * @Date: 2022/8/7 21:20
 * @Description：角色相关接口
 *
 */
@RequestMapping("/role")
@RestController
public class RoleController {

    @Resource
    private ZmRoleMapper zmRoleMapper;

    @Resource
    private ZmRoleService zmRoleService;

    @Resource
    private ZmRoleMenuMapper zmRoleMenuMapper;

    private static Logger logger= LoggerFactory.getLogger(LoginController.class);

    /**
     * 获取所有非删除状态的角色列表
     * @return
     */
    @RequestMapping("/getRoleList")
    public ResultBean getRoleList(RoleDto roleDto){
        ResultBean resultBean=new ResultBean();
        Integer pageNo=1;
        Integer pageSize=10;
        if(ObjectUtil.isNotEmpty(roleDto.getPageNo())){
            pageNo=roleDto.getPageNo();
        }
        if(ObjectUtil.isEmpty(roleDto.getPageSize())){
            pageSize= roleDto.getPageSize();
        }
        try{
            QueryWrapper<ZmRole> wrapper=designWrapper(roleDto);
            IPage<ZmRole> page=new Page<>(pageNo,pageSize);
            IPage<ZmRole> iPage = zmRoleMapper.selectPage(page, wrapper);
            //查总数
            Integer size = zmRoleMapper.selectCount(wrapper);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(iPage).setDataCount(Long.parseLong(size.toString()));
        }catch (Exception e){
            logger.error("查询角色列表接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    QueryWrapper<ZmRole> designWrapper(RoleDto roleDto){
        QueryWrapper<ZmRole> wrapper=new QueryWrapper<>();
        if(StrUtil.isNotEmpty(roleDto.getRoleName())){
            wrapper.lambda().like(ZmRole::getRoleName,roleDto.getRoleName());
        }
        if(StrUtil.isNotEmpty(roleDto.getRoleCode())){
            wrapper.lambda().like(ZmRole::getRoleCode,roleDto.getRoleCode());
        }
        if(StrUtil.isNotEmpty(roleDto.getStatus())){
            wrapper.lambda().eq(ZmRole::getStatus,roleDto.getStatus());
        }
        if(StrUtil.isNotEmpty(roleDto.getStartTime())){
            wrapper.lambda().ge(ZmRole::getCreateTime,roleDto.getStartTime());
        }
        if(StrUtil.isNotEmpty(roleDto.getEndTime())){
            wrapper.lambda().le(ZmRole::getCreateTime,roleDto.getEndTime());
        }
        wrapper.lambda().ge(ZmRole::getStatus, "0");
        return wrapper;
    }

    /**
     * 获取该角色id对应的全部用户及组织信息
     * @param id
     * @return
     */
    @RequestMapping("/getUserAndOrgForRole")
    public ResultBean getUserAndOrgForRole(@RequestParam(value = "id")String id,
                                           @RequestParam(value = "type")String type,
                                           @RequestParam(value = "startIndex")Integer startIndex,
                                           @RequestParam(value = "pageSize")Integer pageSize){
        ResultBean resultBean=new ResultBean();
        try{
            List<UserDto> userDtoList = zmRoleService.selectUserAndOrgForRole(id,startIndex,pageSize,type);
            List<UserDto> userDtos = zmRoleService.selectUserAndOrgForRole(id, 0, 9999999,type);
            Map<String,Object> map=new HashMap<>();
            map.put("dataCount",userDtos.size());
            map.put("data",userDtoList);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(map);
        }catch (Exception e){
            logger.error("查询角色对应菜单权限接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 获取角色对应的菜单权限
     * @param id
     * @return
     */
    @RequestMapping("/getMenuByRole")
    public ResultBean getMenuByRoleId(@RequestParam(value = "id")String id){
        ResultBean resultBean=new ResultBean();
        try{
            QueryWrapper<ZmRoleMenu> wrapper=new QueryWrapper<>();
            List<String> menuIdList=new ArrayList<>();
            List<ZmRoleMenu> zmRoleMenus = zmRoleMenuMapper.selectList(wrapper.lambda().eq(ZmRoleMenu::getRoleId, id));
            if(ObjectUtil.isNotEmpty(zmRoleMenus)){
                for(ZmRoleMenu roleMenu:zmRoleMenus){
                    menuIdList.add(roleMenu.getMenuId());
                }
            }
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(menuIdList);
        }catch (Exception e){
            logger.error("查询角色对应菜单权限接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 获取所有启用状态的角色
     * @return
     */
    @RequestMapping("getAllRole")
    public ResultBean getAllRole(){
        ResultBean resultBean=new ResultBean();
        QueryWrapper<ZmRole> wrapper=new QueryWrapper<>();
        try {
            List<ZmRole> zmRoleList = zmRoleMapper.selectList(wrapper.lambda().eq(ZmRole::getStatus, "1"));
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(zmRoleList);
        }catch (Exception e){
            logger.error("查询已启用角色接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 获取所有角色标识，做唯一校验
     * @return
     */
    @RequestMapping("getAllRoleCode")
    public ResultBean getAllRoleCode(){
        ResultBean resultBean=new ResultBean();
        try{
            List<String> list = zmRoleMapper.selectAllRoleCode();
            resultBean.setCode(ResultBean.CODE_SUCCESS).setData(list);
        }catch (Exception e){
            logger.error("查询全部角色标识接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 取消用户角色授权=>重置为普通角色
     * @return
     */
    @RequestMapping("cancel")
    @SysLogTag(desc = " 取消用户角色授权")
    public ResultBean cancel(@RequestBody List<UserDto> list){
        ResultBean resultBean=new ResultBean();
        try{
            zmRoleService.cancel(list);
            resultBean.setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            logger.error("批量取消用户角色授权接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 分配用户
     * @param map
     * @return
     */
    @RequestMapping("assign")
    @SysLogTag(desc = " 角色分配用户")
    public ResultBean assign(@RequestBody Map<String,Object> map){
        ResultBean resultBean=new ResultBean();
        try{
            //处理参数
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            String roleId="";
            List<UserDto> list=new ArrayList<>();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                if("roleId".equals(entry.getKey())){
                    roleId=entry.getValue().toString();
                    //logger.info("zmRole:{}",zmRole);
                }
                if("list".equals(entry.getKey())){
                    JSONArray array = JSONUtil.parseArray(entry.getValue());
                    list=JSONUtil.toList(array,UserDto.class);
                    //logger.info("menuIdList:{}",menuIdList);
                }
            }
            zmRoleService.assign(roleId,list);
            resultBean.setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            logger.error("批量授权用户角色接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 新增
     * @param map
     * @return
     */
    @RequestMapping("add")
    @SysLogTag(desc = " 角色新增")
    public ResultBean add(@RequestBody Map<String, Object>map){
        ResultBean resultBean=new ResultBean();
        ZmRole zmRole=new ZmRole();
        List<String> menuIdList=new ArrayList<>();
        QueryWrapper<ZmRole> wrapper=new QueryWrapper<>();
        try{
            //参数处理
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                if("roleinfo".equals(entry.getKey())){
                    JSONObject role = JSONUtil.parseObj(entry.getValue());
                    zmRole=JSONUtil.toBean(role,ZmRole.class);
                    //logger.info("zmRole:{}",zmRole);
                }
                if("menuIdList".equals(entry.getKey())){
                    JSONArray array = JSONUtil.parseArray(entry.getValue());
                    menuIdList=JSONUtil.toList(array,String.class);
                    //logger.info("menuIdList:{}",menuIdList);
                }
            }
            zmRole.setCreateTime(DateUtil.date());
            zmRole.setCreateBy("0.0");
            //新增角色
            zmRoleMapper.insert(zmRole);
            //查出新增角色id
            ZmRole role = zmRoleMapper.selectOne(wrapper.lambda().eq(ZmRole::getRoleCode, zmRole.getRoleCode()));
            zmRoleService.batchAdd(role.getId(),menuIdList);
            resultBean.setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            logger.error("新增角色接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 修改
     * @param map
     * @return
     */
    @RequestMapping("update")
    @SysLogTag(desc = " 角色修改")
    public ResultBean update(@RequestBody Map<String,Object> map){
        ResultBean resultBean=new ResultBean();
        ZmRole zmRole=new ZmRole();
        List<String> menuIdList=new ArrayList<>();
        try{
            //参数处理
            Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                if("roleinfo".equals(entry.getKey())){
                    JSONObject role = JSONUtil.parseObj(entry.getValue());
                    zmRole=JSONUtil.toBean(role,ZmRole.class);
                    //logger.info("zmRole:{}",zmRole);
                }
                if("menuIdList".equals(entry.getKey())){
                    JSONArray array = JSONUtil.parseArray(entry.getValue());
                    menuIdList=JSONUtil.toList(array,String.class);
                    logger.info("menuIdList:{}",menuIdList);
                }
            }
            //修改角色信息
            zmRole.setUpdateBy("等待开发捏");
            zmRole.setUpdateTime(DateUtil.date());
            zmRoleMapper.updateById(zmRole);
            //修改角色菜单对应信息
            zmRoleService.batchAdd(zmRole.getId(),menuIdList);
            resultBean.setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            logger.error("修改角色接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }

    /**
     * 删除（含批量
     * @param zmRoles
     * @return
     */
    @RequestMapping("batchDel")
    @SysLogTag(desc = " 角色删除")
    public ResultBean batchDel(@RequestBody  List<ZmRole> zmRoles){
        ResultBean resultBean=new ResultBean();
        try{
            zmRoleService.batchDel(zmRoles);
            resultBean.setCode(ResultBean.CODE_SUCCESS);
        }catch (Exception e){
            logger.error("批量删除角色接口出错：{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR);
        }
        return resultBean;
    }
}
